package us.versus.them.intersect;

import flash.display.Graphics;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.Lib;

class App {
	var vert0:Point;
	var vert1:Point;
	var vert2:Point;

	var center:Point;
	var radius:Float;

	var red:Int;
	var green:Int;
	var blue:Int;

	var tuv:Point;
	var org:Point;
	var dir:Point;

	var i:Int;
	var j:Int;

	public function new() {
		reset();

		tuv = Intersect.threePt();
		org = Intersect.threePt();
		dir = Intersect.threePt();

		flash.Lib.current.addEventListener( Event.ENTER_FRAME, loop );
		flash.Lib.current.stage.addEventListener( MouseEvent.MOUSE_DOWN, mouseDown );
		flash.Lib.current.graphics.clear();
	}

	public function reset() { 
		vert0 = Intersect.represent( w(), h(), -w() );
		vert1 = Intersect.represent( w(), h(), -w() );
		vert2 = Intersect.represent( w(), h(), -w() );

		red   = Math.floor( Math.random() * 192 ) + 32;
		green = Math.floor( Math.random() * 192 ) + 32;
		blue  = Math.floor( Math.random() * 192 ) + 32;

		center = Intersect.represent( w(), h(), -w() );
		radius = h() * 0.25;

		i = j = 0;
	}

	public function w() {
		return Math.random() * flash.Lib.current.stage.stageWidth;
	}
	public function h() {
		return Math.random() * flash.Lib.current.stage.stageHeight;
	}

    public function loop( _ ) {
		for ( i in 0 ... 1000 ) {
			meh();
		}
	}

	public function meh() {
		feh();
		j++;
		if ( j > flash.Lib.current.stage.stageWidth ) {
			j = 0;
			i++;
		}
		if ( i > flash.Lib.current.stage.stageHeight ) {
			reset();
		}
	}

	public function feh() {
		org.x = ( j );
		org.y = ( i );
		dir.z = ( -flash.Lib.current.stage.stageHeight );

		var hit = Intersect.intersect_triangle_non_culling(
			org
			, dir
			, vert0
			, vert1
			, vert2
			, tuv
		);
		if ( 1 == hit ) {
			drawHit( tuv.x );
		}

		var when = Intersect.intersect_sphere(
			org
			, dir
			, center
			, radius
		);
		if ( when >=0 && when <= 1 ) {
			drawHit( when );
		}
	}

	public function drawHit( t:Float ) {
		if ( t > 0&& t < 1 ) {
			flash.Lib.current.graphics.lineStyle( 
				1
				, ( 0
					| ( 65536 * Math.floor( t * red )   )
					| (   255 * Math.floor( t * green ) )
					| (     1 * Math.floor( t * blue )  )
				)
			);
			flash.Lib.current.graphics.drawCircle( j,i , 1 );
		}
	}

	public function mouseDown( _ ) {
		reset();
	}
}
